package a51qindian.com.comprehensive.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.widget.ImageView;

import com.li.widget.MultipleLayout;
import com.li.widget.TopNavigationBar;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import a51qindian.com.comprehensive.R;
import a51qindian.com.comprehensive.base.QDBaseActivity;
import a51qindian.com.comprehensive.net.ObservableHelper;
import a51qindian.com.comprehensive.net.RetrofitCreator;
import butterknife.BindView;
import butterknife.OnClick;
import cn.bingoogolapple.qrcode.core.QRCodeView;
import cn.bingoogolapple.qrcode.zbar.ZBarView;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

/**
 * Author: Li
 * Date: 2017/9/18 0018
 * Description: 二维码扫描
 */

public class QRCodeActivity extends QDBaseActivity {

    private static final int REQUEST_CAMERA_CODE = 402;
    @BindView(R.id.top_navigation)
    TopNavigationBar mTopNavigation;
    @BindView(R.id.qr_view)
    ZBarView mQrView;
    @BindView(R.id.img_light)
    ImageView mImgLight;
    @BindView(R.id.layout_content)
    MultipleLayout mLayoutContent;

    private String mSource;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_qrcode;
    }

    @Override
    protected void initSth() {
        super.initSth();
        mTopNavigation.setNavigationBarListener(this);
        mSource = getIntent().getStringExtra("source");
        switch (mSource) {
            case "install":
                mTopNavigation.setTxtFunctionVisible(View.GONE);
                break;

        }
        //相机权限验证
        switch (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)) {
            case PackageManager.PERMISSION_GRANTED:
                startScan();
                break;
            case PackageManager.PERMISSION_DENIED:
                ActivityCompat.requestPermissions(QRCodeActivity.this,
                        new String[]{Manifest.permission.CAMERA}, REQUEST_CAMERA_CODE);
                break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        startScan();
    }

    @Override
    public void onFunctionTxtListener(View view) {
        super.onFunctionTxtListener(view);
        startActivity(new Intent(this, CouponListActivity.class));
    }

    /**
     * 开始扫描
     */
    private void startScan() {
        mQrView.setDelegate(new QRCodeView.Delegate() {
            @Override
            public void onScanQRCodeSuccess(String result) {
                int index;
                mQrView.closeFlashlight();
                switch (mSource) {
                    case "install":
                        if (!result.contains("http://we.qq.com")) {
                            showToast("请扫描小随设备");
                            finish();
                            return;
                        }
                        index = result.indexOf("#") + 1;
                        Intent resultIntent = new Intent();

                        resultIntent.putExtra("sn", result.substring(index));
                        setResult(RESULT_OK, resultIntent);
                        finish();
                        break;
                    case "add":
                        Intent intent = new Intent();
                        intent.putExtra("name", result);
                        setResult(RESULT_OK, intent);
                        finish();
                        break;
                    default:
                        verifyCoupon(mUid, result);

                        break;
                }

            }

            @Override
            public void onScanQRCodeOpenCameraError() {
                showToast("相机权限未打开");
            }
        });
        mQrView.startCamera();
        mQrView.startSpot();
    }

    @OnClick(R.id.img_light)
    public void onViewClicked() {
        if (mImgLight.isSelected()) {
            mQrView.closeFlashlight();
            mImgLight.setSelected(false);
        } else {
            mQrView.openFlashlight();
            mImgLight.setSelected(true);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mQrView.closeFlashlight();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_CAMERA_CODE &&grantResults[0]==PackageManager.PERMISSION_GRANTED) {
            startScan();
        }else {
            showToast("请打开相机权限");
        }
    }

    private void verifyCoupon(String uid, String sn) {
        mLayoutContent.onLoadingWithContent("正在验证");
        Map<String, String> map = new HashMap<>();
        map.put("uid", uid);
        map.put("sn", sn);
        ObservableHelper.createObservable(RetrofitCreator.createService().verifyCoupon(map))
                .subscribe(new Observer<String>() {
                    @Override
                    public void onSubscribe(@io.reactivex.annotations.NonNull Disposable d) {
                        addDisposable(d);
                    }

                    @Override
                    public void onNext(@io.reactivex.annotations.NonNull String s) {
                        mLayoutContent.onSuccess();
                        try {
                            JSONObject object = new JSONObject(s);
                            if (object.getInt("code") != 1) {
                                showToast(object.getString("info"));
                                startScan();
                            } else {
                                startActivity(new Intent(QRCodeActivity.this, CouponListActivity.class));
                                finish();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onError(@io.reactivex.annotations.NonNull Throwable e) {
                        mLayoutContent.onSuccess();
                        showToast(e.getMessage());
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }
}
